<?php

function get_videos_in_playlist( $username, $playlist_id )
{
	if ( (time() - filemtime(the_file_contents($username, $playlist_id) )) > 3 ) {
		$perPage = 50;
		$start = 1;
		$videos = array();
	
		do {
			// $data = file_get_contents("http://gdata.youtube.com/feeds/api/users/{$username}/uploads?start-index={$start}&max-results={$perPage}");
			$data = file_get_contents("http://gdata.youtube.com/feeds/api/playlists/{$playlist_id}?v=2");
			$xml = simplexml_load_string( $data );
			
			// print_r( $xml );
			// return;
			
			$last = (array)(( isset($xml->link[6])) ? $xml->link[6] : $xml->link[5] );
		
			foreach ( $xml->entry as $video )
			{
				$title	= (array)$video->title;
				$title = $title[0];
				
				$url = (array)$video->link[4];
				$url = substr($url['@attributes']['href'], 0, strlen( $url['@attributes']['href']) - 4);
				$urls = explode( '/', $url );
				$url = $urls[ count($urls)-1 ];
				
				$desc 	= get_description( $url );
				if ( isset( $desc[0] ) ) {	
					$desc = $desc[0];
				} else {
					$desc = "No description found.";
				}
				
				$imgs = array( 
					"http://img.youtube.com/vi/{$url}/1.jpg", 
					"http://img.youtube.com/vi/{$url}/2.jpg", 
					"http://img.youtube.com/vi/{$url}/3.jpg"
				);
				
				$videos[] = array(
					'title'		=> $title,
					'desc'		=> $desc,
					'url'		=> $url,
					'imgs'		=> $imgs,
					);
			}
		
			$start += $perPage;
		
		} while ( empty($last) === false && $last['@attributes']['rel'] === 'next' );
		
		file_put_contents(the_file_contents($username, $playlist_id), serialize($videos));
		
	} else {
		$videos = unserialize( file_get_contents(the_file_contents($username, $playlist_id)) );
	}
	
	return $videos;
}

function get_description($id) 
{
	$data = file_get_contents("http://gdata.youtube.com/feeds/api/videos/" . $id);
	$xml = simplexml_load_string($data);
	
	$desc = (array)$xml->content;
	
	// print_r( $xml );
	
	return $desc;
}

function get_playlists( $username )
{
	$data = file_get_contents("http://gdata.youtube.com/feeds/api/users/{$username}/playlists/");
	$xml = simplexml_load_string( $data );
	print_r( $xml );
}

function the_file_contents ( $username, $type ) {
	return "{$GLOBALS['path']}/cache/{$username}_{$type}_cache.txt";
}

?>